package ru.papergames.web.npc;

import ru.common.hibernate.HibernateActionExecutor;
import ru.papergames.common.form.NpcPlayerForm;
import ru.papergames.web.blines.battle.BattleServersManager;
import ru.papergames.web.blines.battle.model.BattleOrder2;
import ru.papergames.web.services.GetNpcPlayers;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Date: 12.05.12 9:14
 *
 * @author Alexander Troshanin
 */
public class NpcsManager {

    private static NpcsManager instance = new NpcsManager();

    private Map<Long, NpcPlayerForm> freeNpcs = new ConcurrentHashMap<Long, NpcPlayerForm>();

    private Map<Long, NpcPlayerForm> fightingNpcs = new ConcurrentHashMap<Long, NpcPlayerForm>();

    public static NpcsManager getInstance() {
        return instance;
    }

    public void init(HibernateActionExecutor hiber) {
        List<NpcPlayerForm> npcPlayers = hiber.execute(new GetNpcPlayers());
        for (NpcPlayerForm npcPlayer : npcPlayers) {
            freeNpcs.put(npcPlayer.getId(), npcPlayer);
        }

        while (!BattleServersManager.getInstance().addNpcPlayersToBattleServer(npcPlayers)) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // skip it
            }
        }
    }

    public Collection<NpcPlayerForm> getFreeNpcsSet() {
        return freeNpcs.values();
    }

    public void addNpcInBattleOrder(NpcPlayerForm npcPlayer, BattleOrder2 battleOrder, int team) {
        battleOrder.addBattleNpcMember(npcPlayer, team);
        freeNpcs.remove(npcPlayer.getId());
        fightingNpcs.put(npcPlayer.getId(), npcPlayer);
    }
}
